(function() {

	nsbase.views.login = new LoginFunc();

	function LoginFunc() {
		var _self = this;

		_self.init = init;

		var indexActions = nsbase.config.actionUrl.index,
			utilities = nsbase.utility,
			validations = nsbase.utility.validations,
        	clientResource = nsbase.resources.clientResource;

		var errorClass = "error",successClass = "success";

		var cookieKeys = {
			email:"et_email",
			pwd:"et_pwd"
		};
		function init() {
			// bind form control events
			bindLoginForm();
			bindRegisterForm();
			bindForgetForm();
		}

		// bind login form control events
		function bindLoginForm() {
			var loginContainer = $(".loginContainer"),
				btnLogin = loginContainer.find(".btnLogin"),
				txtEmail = loginContainer.find(".txtEmail"),
				txtPwd = loginContainer.find(".txtPwd");

			var cookieEmail = nsbase.cookie.get(cookieKeys.email);
			var cookiePwd = nsbase.cookie.get(cookieKeys.pwd);
			txtEmail.val(cookieEmail);
			txtPwd.val(cookiePwd);
			loginContainer.keypress(function(e){
				if(e.keyCode == 13){
					$(this).find(".btnLogin").click();
				}
			});
			$(".linkLogin").click(function() {
				loginContainer.dialog();
			});

			loginContainer.find("input[type !='checkbox']").blur(function() {
				var sender = $(this);
				inputEmptyValidate([sender]);
			});

			txtEmail.blur(function() {
				inputEmailValidate($(this));
			});

			btnLogin.click(function() {
				var sender = $(this),
					loginForm = sender.parents(".loginContainer"),
					txtEmail = loginForm.find(".txtEmail"),
					txtPwd = loginForm.find(".txtPwd"),
					loadingDiv = loginForm.find(".loading");

				inputEmptyValidate([txtEmail, txtPwd]);
				inputEmailValidate(txtEmail);
				if (loginForm.find("." + errorClass).length > 0) {
					return false;
				}
				loadingDiv.css("width",sender.width()+20).show();
				var param = {
					email: txtEmail.val(),
					password: txtPwd.val(),
					remember_me: loginForm.find(".chkRember").prop("checked") ? 1 : 0
				}
				nsbase.ajax.request(indexActions.login, param, function(result) {
					loadingDiv.hide();
					if(result.success){
						if(param.remember_me == 1){
							nsbase.cookie.set(cookieKeys.email,param.email,new Date("9999-12-31"));
							nsbase.cookie.set(cookieKeys.pwd,param.password,new Date("9999-12-31"));
						} else {
							nsbase.cookie.clear(cookieKeys.email);
							nsbase.cookie.clear(cookieKeys.pwd);
						}
						location.href = nsbase.config.actionUrl.dashboard.index;
					} else {
						loginForm.find(".result").text(result.message).slideDown();
					}
				},function () {
					loadingDiv.hide();
				});
			});
		}

		// bind register form control events

		function bindRegisterForm() {
			var registerContainer = $(".registerContainer"),
				btnRegister = registerContainer.find(".btnRegister"),
				txtUserName = registerContainer.find(".txtUserName"),
				txtEmail = registerContainer.find(".txtEmail"),
				txtPwd = registerContainer.find(".txtPwd"),
				txtConfirmPwd = registerContainer.find(".txtConfirmPwd");

			registerContainer.keypress(function(e){
				if(e.keyCode == 13){
					$(this).find(".btnRegister").click();
				}
			});

			$(".linkRegister").click(function() {
				registerContainer.dialog();
			});

			registerContainer.find("input").blur(function() {
				var sender = $(this);
				inputEmptyValidate([sender]);
			});

			// validate emial format and emial is used by others
			txtEmail.blur(function() {
				var sender = $(this),
					msgSpan = sender.next("span");
				inputEmailValidate(sender);
				if (msgSpan.hasClass(errorClass)) {
					return false;
				}
				msgSpan.addClass("loading");
				var param = {
					email: sender.val()
				};
				// sync validate user email is used or not
				nsbase.ajax.request(indexActions.validateEmail, param, function(result) {
					msgSpan.removeClass("loading");
					if(result.success){
						msgSpan.addClass(successClass);
					} else {
						msgSpan.addClass(errorClass).text(result.message);
					}
				},function(){
					msgSpan.removeClass("loading");
				});
			});

			// validate password is match confirm password
			$.merge(txtConfirmPwd, txtPwd).blur(function() {
				var sender = $(this),
					registerForm = sender.parents(".registerContainer"),
					pwd = registerForm.find(".txtPwd").val(),
					txtConfirmPwd = registerForm.find(".txtConfirmPwd"),
					confirmPwd = txtConfirmPwd.val();
					msgSpan = sender.parent().find("span:last"),
					confirmMsgSpan = txtConfirmPwd.parent().find("span:last");
			
				if (!msgSpan.hasClass(errorClass) && pwd.length > 0 && confirmPwd.length > 0) {
					if(pwd !== confirmPwd){
						confirmMsgSpan.addClass(errorClass).text(clientResource.msgNotMatchPwd);
					} else {
						confirmMsgSpan.removeClass(errorClass).empty();
					}
				} 
			});

			btnRegister.click(function() {
				var sender = $(this),
					registerForm = sender.parents(".registerContainer"),
					txtUserName = registerForm.find(".txtUserName"),
					txtEmail = registerForm.find(".txtEmail"),
					txtPwd = registerForm.find(".txtPwd"),
					txtConfirmPwd = registerForm.find(".txtConfirmPwd"),
					loadingDiv = registerForm.find(".loading");

				inputEmptyValidate([txtUserName, txtEmail, txtPwd,txtConfirmPwd]);
				inputEmailValidate(txtEmail);
				if (registerForm.find("." + errorClass).length > 0) {
					return false;
				}

				loadingDiv.css("width",sender.width()+20).show();
				var param = {
					userName: txtUserName.val(),
					email: txtEmail.val(),
					password: txtPwd.val()
				}
				nsbase.ajax.request(indexActions.register, param, function(result) {
					loadingDiv.hide();
					var resultContainer = registerForm.find(".result").slideDown();
					if(result.success){
						resultContainer.text(clientResource.msgActivate);
					} else {
						resultContainer.text(result.message);
					}
				},function(){
					loadingDiv.hide();
				});

			});

		}

		// bind forget password form control events
		function bindForgetForm() {
			var forgetContainer = $(".forgetContainer"),
				btnReset = forgetContainer.find(".btnReset"),
				txtEmail = forgetContainer.find(".txtEmail");

			forgetContainer.keypress(function(e){
				if(e.keyCode == 13){
					$(this).find(".btnReset").click();
				}
			});

			$(".linkForget").click(function () {
				forgetContainer.dialog();
			});
			txtEmail.blur(function() {
				var sender = $(this),
					msgSpan = sender.parent().find("span:last");
				inputEmptyValidate([sender]);
				inputEmailValidate(sender);

				if (msgSpan.hasClass(errorClass)) {
					return false;
				}
				msgSpan.addClass("loading");
				var param = {
					email: sender.val()
				};
				// sync validate user email is used or not
				nsbase.ajax.request(indexActions.validateEmail, param, function(result) {
					msgSpan.removeClass("loading");
					if(result.success){
						msgSpan.addClass(errorClass).text(clientResource.msgNotExistEmail);
					} 
				},function(){
					msgSpan.removeClass("loading");
				});
			});

			btnReset.click(function() {
				var sender = $(this),
					forgetForm = sender.parents(".forgetContainer"),
					txtEmail = forgetForm.find(".txtEmail"),
					loadingDiv = forgetForm.find(".loading");

				inputEmptyValidate([txtEmail]);
				inputEmailValidate(txtEmail);
				if (forgetForm.find("." + errorClass).length > 0) {
					return false;
				}

				loadingDiv.css("width",sender.width()+20).show();
				var param = {
					email: txtEmail.val()
				}
				nsbase.ajax.request(indexActions.forgetPwd, param, function(result) {
					loadingDiv.hide();
					var resultContainer = forgetForm.find(".result").slideDown();
					if(result.success){
						resultContainer.text(clientResource.msgFindPwd);
					} else {
						resultContainer.text(result.message);
					}
				},function(){
					loadingDiv.hide();
				});
			});
		}

		// validate input type = 'text' is empty or not
		function inputEmptyValidate(inputs) {
			$.each(inputs, function(i, item) {
				var labelDesc = utilities.trimEnd(item.prev().text(),'：'),
					msgSpan = item.parent().find("span:last");
				msgSpan.removeClass(errorClass).empty();

				if (!utilities.trim(item.val())) {
					msgSpan.addClass(errorClass).text(utilities.stringFormat(clientResource.msgNoEmpty, labelDesc));
				}
			});
		}

		// validate email
		function inputEmailValidate ($input) {
			var emailvalue = utilities.trim($input.val()),
				msgSpan = $input.parent().find("span:last");
			if (!msgSpan.hasClass(errorClass) && !validations.emailValidate(emailvalue)) {
				msgSpan.addClass(errorClass).text(clientResource.msgInvalidEmail);
			}
		}
	}
})();